from flask import request, jsonify, current_app, Blueprint
from task_app.tasks import add_apscheduler, edit_apscheduler
from task_app.extensions import scheduler
from extensions import db
from task_app.models import JobPlan

job_bp = Blueprint('job', __name__)


@job_bp.route('/test/', methods=['GET', 'POST'])
def test():
    current_app.logger.info("执行我的任务test，bababa....")
    values = request.values.to_dict()
    values['method'] = 'GET' if request.method == 'GET' else 'POST'
    values['app'] = 'TASK APP'
    return jsonify(values)


# 新增job
@job_bp.route('/addCron/', methods=['post'])
def add_cron():
    """
    添加interval类型定时任务,参数格式如下：
    {
        "app_name":"task_app",
        "task_id": "1111",
        "name":"测试1111",
        "method":"GET",
        "url":"http://localhost:5000/task/test/?name=Cherish",
        "params":{"trigger_type":"interval"},
        "trigger_type": "interval",
        "trigger_kwargs":{
            "weeks":"",
            "days":"",
            "hours":"",
            "minutes":"",
            "seconds":"10",
            "start_date":"2021-11-25 17:00:00",
            "end_date":"3021-11-25 17:00:00"
        }
    }

    添加cron类型定时任务,入参格式如下：
    {
        "app_name":"task_app",
        "task_id": "333",
        "name":"测试333",
        "method":"GET",
        "url":"http://localhost:5000/task/test/?name=Cherish",
        "params":{"trigger_type":"cron"},
        "trigger_type": "cron",
        "trigger_kwargs": {
            "year":"*",
            "month":"*",
            "day":"*",
            "week":"*",
            "day_of_week": "*",
            "hour": "*",
            "minute": "*",
            "second": "*/10",
            "start_date":"2021-11-25 17:00:00",
            "end_date":"3021-11-25 17:00:00"
            }
    }

    添加date类型定时任务,入参格式如下：
    {
        "app_name":"task_app",
        "task_id": "222",
        "name":"测试222",
        "method":"POST",
        "url":"http://localhost:5000/task/test/?name=Cherish",
        "params":{"trigger_type":"date"},
        "trigger_type": "date",
        "trigger_kwargs": {
            "run_date":"2021-11-25 17:30:00"
            }
    }



    """

    # 获取入参，校验入参
    values = request.get_json()
    app_name = values.get("app_name")
    task_id = values.get("task_id").strip()
    if not task_id: return jsonify(code=1002, msg="缺少必要参数：task_id")
    task_name = values.get("name")
    method = values.get("method", "GET")
    url = values.get("url")
    params = values.get("params", {})
    trigger_type = values.get("trigger_type")
    trigger_kwargs = values.get("trigger_kwargs")

    if not isinstance(trigger_kwargs, dict):
        return jsonify(code=1003, msg="trigger_kwargs参数有误：不是字典对象")

    if not isinstance(params, dict):
        return jsonify(code=1003, msg="params参数有误：不是字典对象")

    # 添加或更新业务job表
    plan = JobPlan.query.filter(JobPlan.task_id == task_id).first()
    if not plan: plan = JobPlan()
    plan.app_name = app_name
    plan.task_id = task_id
    plan.name = task_name
    plan.method = method
    plan.url = url
    plan.params = params
    plan.trigger_type = trigger_type
    plan.trigger_kwargs = trigger_kwargs
    plan.status = 1
    db.session.add(plan)
    try:
        db.session.commit()
        # 添加apscheduler job
        add_apscheduler(plan)
    except Exception as e:
        db.session.rollback()
        return jsonify(code=1004, msg="添加业务job失败,失败原因：%s" % str(e))

    return jsonify(code=1001, msg="新增/更新任务成功", job_id=task_id)


# 暂停
@job_bp.route('/pause/<task_id>/', methods=['GET'])
def pause_job(task_id):
    response = {'status': False}
    try:
        plan = JobPlan.query.filter(JobPlan.task_id == task_id).first_or_404()
        plan.status = 2
        db.session.commit()
        # 更新 apscheduler 状态
        edit_apscheduler(plan)
        response['status'] = True
        response['msg'] = "job[%s] pause success!" % task_id
    except Exception as e:
        response['msg'] = str(e)
    return jsonify(response)


# 恢复job
@job_bp.route('/resume/<task_id>/', methods=['GET'])
def resume_job(task_id):
    response = {'status': False}
    try:
        plan = JobPlan.query.filter(JobPlan.task_id == task_id).first_or_404()
        plan.status = 1
        db.session.commit()
        # 更新 apscheduler 状态
        edit_apscheduler(plan)
        response['status'] = True
        response['msg'] = "job[%s] resume success!" % task_id
    except Exception as e:
        response['msg'] = str(e)
    return jsonify(response)


# 删除job
@job_bp.route('/remove/<task_id>/', methods=['GET', 'POST'])
def remove_job(task_id):
    response = {'status': False}
    try:
        result = request.values.get("result")
        plan = JobPlan.query.filter(JobPlan.task_id == task_id).first_or_404()
        plan.status = 3
        db.session.commit()
        scheduler.remove_job(task_id)
        response['status'] = True
        response['msg'] = "job[%s] remove success!" % task_id
    except Exception as e:
        response['msg'] = str(e)
    return jsonify(response)


@job_bp.route('/list/', methods=['GET'])
def get_jobs():
    ret_list = scheduler.get_jobs()
    jobs_list = []
    for item in ret_list:
        task_id = item.id
        plan = JobPlan.query.filter(JobPlan.task_id == task_id).first()
        jobs_list.append(
            {
                "id": item.id,
                "next_run_time": item.next_run_time,
                "name": plan.name,
                "method": plan.method,
                "url": plan.method,
                "params": plan.params,
                "trigger_type": plan.trigger_type,
                "trigger_kwargs": plan.trigger_kwargs,
                "status": plan.status_desc
            }
        )
    return jsonify(jobs_list)


@job_bp.route('/detail/<string:task_id>', methods=['GET'])
def get_detail(task_id):
    ret_list = scheduler.get_job(task_id)

    print(ret_list)
    print(ret_list.next_run_time)
    return jsonify({"jobs_list": "OK"})
